using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using BoOnce.Core.Helpers;

namespace BoOnce.Core.Components
{
    public class BackgroundTaskComponent : GameComponent
    {

        public BackgroundTaskComponent(Game game)
            : base(game)
        {
            _Tasks = new LinkedList<BackgroundTask>();
            _TasksToRemove = new LinkedList<BackgroundTask>();
            _TasksToAdd = new LinkedList<BackgroundTask>();
        }

        private LinkedList<BackgroundTask> _Tasks;
        private LinkedList<BackgroundTask> _TasksToRemove;
        private LinkedList<BackgroundTask> _TasksToAdd;

        public override void Initialize()
        {
            Logger.WriteInfo("BackgroundTaskComponent[#"+this.UpdateOrder+"] init");
        }

        public override void Update(GameTime gameTime)
        {
            //Add
            foreach (BackgroundTask task in _TasksToAdd)
            {
                _Tasks.AddFirst(task);
            }

            // Update
            foreach (BackgroundTask task in _Tasks)
            {
                if (task.IsDone())
                {
                    _TasksToRemove.Remove(task);
                }
                else
                {
                    task.Update(gameTime);
                }
            }

            // Remove
            foreach (BackgroundTask task in _TasksToRemove)
            {
                _Tasks.Remove(task);
            }
            _TasksToRemove.Clear();

        }

        public void Add(BackgroundTask task)
        {
            _TasksToAdd.AddFirst(task);
        }

        public void Clear()
        {
            foreach (BackgroundTask task in _Tasks)
            {
                if (!task.IsDone())
                {
                    task.Kill();
                }
            }
            _Tasks.Clear();
            if (_TasksToAdd.Count != 0)
            {
                Logger.WriteWarning(this,"TaskToAdd not EMPTY before cleanning");
                _TasksToAdd.Clear();
            }

            if (_TasksToRemove.Count != 0)
            {
                Logger.WriteWarning(this,"TaskToRemove not EMPTY before cleanning, some tasks maybe not kill properly");
                _TasksToRemove.Clear();
            }
        }
    }
}
